﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContracts;
using ServiceContracts;

namespace Presention
{
    public partial class UpdateAuthority : System.Web.UI.Page
    {
        private static String authorityId;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (ServiceAgent proxy = new ServiceAgent())
                {
                    //Put All LevelName into UpdateLevel
                    this.UpdateLevel.DataSource = proxy.ServiceClient.GetAllAuthorityLevel();
                    this.UpdateLevel.DataTextField = "LevelName";
                    this.UpdateLevel.DataValueField = "LevelId";
                    this.UpdateLevel.DataBind();
                    UpdateLevel.Items.Insert(0, new ListItem("", ""));

                    //Put AuthorityName into TextBox
                    authorityId = Request.QueryString["id"].ToString();
                    //Get Authority Details
                    AuthorityDTO authorityDetails = proxy.ServiceClient.GetAuthorityById(int.Parse(authorityId));
                    this.UpdateName.Text = authorityDetails.AuthorityName;

                    //Get Current LevelName
                    for (int i = 0; i < this.UpdateLevel.Items.Count; i++)
                    {
                        if (this.UpdateLevel.Items[i].Value == authorityDetails.Level.LevelId.ToString())
                        {
                            this.UpdateLevel.Items[i].Selected = true;
                        }
                    }
                }
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
                using (ServiceAgent proxy = new ServiceAgent())
                {
                    string newUpdateName = UpdateName.Text;
                    string newLevelName = this.UpdateLevel.SelectedItem.Text;

                    AuthorityDTO authority = new AuthorityDTO();
                    AuthorityLevelDTO authorityLevelDTO = new AuthorityLevelDTO();
                    authority.Level = authorityLevelDTO;
                    authority.AuthorityName = newUpdateName;
                    authority.Level.LevelId = int.Parse(UpdateLevel.SelectedValue);
                    authority.AuthorityId = int.Parse(authorityId);
                    proxy.ServiceClient.UpdateAuthority(authority);
                    authority.Level.LevelName = UpdateLevel.SelectedItem.Text;
                    Response.Redirect("AuthorityList.aspx");
                }
        }
    }
}